package com.baozun.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baozun.mapper.TUserInfoMapper;
import com.baozun.model.TUserInfo;
import com.baozun.model.TUserInfoExample;
import com.baozun.model.TUserInfoExample.Criteria;
import com.baozun.service.UserInfoService;
import com.baozun.util.PageData;

@Service("userInfoService")
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private TUserInfoMapper userInfoMapper;

    @Override
    public TUserInfo getUserInfoByUserId(String stUserId) {
        TUserInfoExample record = new TUserInfoExample();
        Criteria criteria = record.createCriteria();
        criteria.andStUserIdEqualTo(stUserId);
        record.or(criteria);
        List<TUserInfo> userInfoList = this.getList(record);
        TUserInfo userInfo = CollectionUtils.isEmpty(userInfoList) ? new TUserInfo() : userInfoList.get(0);
        return userInfo;
    }

    @Override
    public void add(TUserInfo bean) {
        if(StringUtils.isEmpty(bean.getStUserInfoId())){
            bean.setStUserInfoId(UUID.randomUUID().toString());
        }
        bean.setDtUpdateTime(new Date());
        userInfoMapper.insert(bean);
    }

    @Override
    public TUserInfo get(String id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(TUserInfo bean) {
        userInfoMapper.updateByPrimaryKeyWithBLOBs(bean);
    }

    @Override
    public void delete(String stUserInfoId) {
        userInfoMapper.deleteByPrimaryKey(stUserInfoId);
    }

    @Override
    public PageData<TUserInfo> getPageListByExample(TUserInfoExample record, int pageSize, int currentPage) {
        record.setSize(pageSize);
        record.setStart(pageSize * (currentPage - 1));
        PageData<TUserInfo> infoList = new PageData<TUserInfo>();
        List<TUserInfo> appendixList = userInfoMapper.selectByExampleWithBLOBs(record);
        int count = userInfoMapper.countByExample(record);
        infoList.addAll(appendixList);
        infoList.setPage(currentPage);
        infoList.setPages((count + pageSize - 1) / pageSize);
        infoList.setPageSize(pageSize);
        infoList.setTotalRecords(count);
        return infoList;
    }

    @Override
    public List<TUserInfo> getList(TUserInfoExample record) {
        return userInfoMapper.selectByExampleWithBLOBs(record);
    }
}
